<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-row>
        <el-col :span="15">
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves icon="el-icon-plus" v-if="!paymentForm.id" @click="addPaymentClick()">新增</el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves icon="el-icon-edit" v-else-if="paymentForm.id && paymentForm.status == 0" @click="updatePaymentClick">保存</el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves icon="el-icon-share" v-if="paymentForm.status == undefined || paymentForm.status == 0" @click="relevanceShouldPaymentClick">关联应付单</el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves icon="el-icon-delete" @click="cleanClick">清空</el-button>
        </el-col>
      </el-row>
    </div>
    <div style="clean:both"></div>

    <el-container class="el-container">
      <el-main>
        <el-form :rules="paymentFormRules" ref="paymentForm" :inline="true" :model="paymentForm" label-position="left" label-width="100px" class="demo-form-inline">

          <el-form-item label="结算公司" prop="settlCompanyId">
            <el-select v-model="paymentForm.settlCompanyId" placeholder="请选择结算公司">
              <el-option v-for="company in companyList" :key="company.id" :label="company.name" :value="company.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="单据类型" prop="docType">
            <el-select v-model="paymentForm.docType" placeholder="请选择单据类型">
              <el-option v-for="shouldPaymentType in shouldPaymentTypeList" :key="shouldPaymentType.id" :label="shouldPaymentType.name" :value="shouldPaymentType.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="会计期间" prop="fiscalPeriod">
            <el-select class="fsc-input" v-model="paymentForm.fiscalPeriod" placeholder="请选择会计期间">
              <el-option v-for="fiscalPeriod in fiscalPeriodList" :key="fiscalPeriod.id" :label="fiscalPeriod.name" :value="fiscalPeriod.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="付款日期" prop="paymentDate">
            <el-date-picker class="fsc-input" v-model="paymentForm.paymentDate" value-format="yyyy-MM-dd" type="date" placeholder="请选择付款日期"></el-date-picker>
          </el-form-item>

          <el-form-item label="供应商" prop="partnerId">
            <el-select v-model="paymentForm.partnerId" filterable placeholder="请选择供应商">
              <el-option v-for="partner in partnerList" :key="partner.id" :label="partner.ncName" :value="partner.id"></el-option>
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="部门" prop="department">
            <el-select v-model="paymentForm.departmentId" placeholder="请选择部门">
              <el-option v-for="department in departmentList" :key="department.id" :label="department.name" :value="department.id"></el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item label="单据日期" prop="docDate">
            <el-date-picker class="fsc-input" v-model="paymentForm.docDate" value-format="yyyy-MM-dd" type="date" placeholder="请选择单据日期"></el-date-picker>
          </el-form-item>

          <!-- <el-form-item label="业务员" prop="staffId">
            <el-select v-model="paymentForm.staffId" placeholder="请选择业务员">
              <el-option v-for="staff in staffList" :key="staff.id" :label="staff.name" :value="staff.id"></el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item label="收付款协议" prop="agreementId">
            <el-select v-model="paymentForm.agreementId" placeholder="请选择收付款协议">
              <el-option label="一日月结" value="10"></el-option>
              <el-option label="三十日月结" value="20"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="现金流量" prop="cashFlowLtem">
            <el-select v-model="paymentForm.cashFlowLtem" filterable placeholder="请选择现金流量">
              <el-option v-for="cashFlowLtem in cashFlowLtemList" :key="cashFlowLtem.id" :label="cashFlowLtem.name" :value="cashFlowLtem.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input class="fsc-input" v-model="paymentForm.remark" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-form>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>行</span>
            <el-button type="primary" style="margin:10px" icon="el-icon-plus" @click="addPaymentFormRowClick"></el-button>
            <el-button type="primary" style="margin:10px" icon="el-icon-minus" @click="deletePaymentFormRowClick"></el-button>
          </div>
          <div>
            <el-table ref="paymentFormRowTable" :data="paymentForm.paymentRowsDetailList" v-loading="listLoading" element-loading-text="加载中" border fit highlight-current-row style="width: 100%;margin-top:5px">
              <el-table-column type="selection" width="40"></el-table-column>
              <el-table-column align="center" label="结算方式">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.settleTypeId" placeholder="请选择结算方式">
                    <el-option v-for="settleType in settleTypeList" :key="settleType.id" :label="settleType.name" :value="settleType.id"></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column align="center" label="付款总额">
                <template slot-scope="scope">
                  <el-input v-model.number="scope.row.ocAmt" placeholder="请输入付款总额"></el-input>
                </template>
              </el-table-column>

              <el-table-column align="center" label="付款银行">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.payBankId" placeholder="请选择付款银行" @change="selectBankInfoChange(scope)">
                    <el-option v-for="bankInfo in bankInfoList" :key="bankInfo.id" :label="bankInfo.name" :value="bankInfo.id"></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column align="center" label="付款账号">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.payAccountCode" placeholder="请选择付款账号">
                    <el-option v-for="bankAccount in bankAccountList[scope.$index]" :key="bankAccount.id" :label="bankAccount.code" :value="bankAccount.code"></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column align="center" label="用途">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.useWay" placeholder="请选择用途">
                    <el-option label="标准" value="10"></el-option>
                    <el-option label="预付" value="20"></el-option>
                    <el-option label="保证金" value="30"></el-option>
                    <el-option label="杂项" value="40"></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column align="center" label="主体公司">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.mainCompanyId" placeholder="请选择主体公司">
                    <el-option v-for="company in companyList" :key="company.id" :label="company.name" :value="company.id"></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column align="center" label="摘要">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.summary" placeholder="请输入摘要"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <div>总金额:{{rowMoneyCount}}</div>
          </div>
        </el-card>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>付款明细</span>
          </div>
          <div>
            <el-table ref="paymentFormDetailTable" :data="paymentForm.paymentDetailList" v-loading="listLoading" element-loading-text="加载中" border fit highlight-current-row style="width: 100%;margin-top:5px">
              <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
              <el-table-column label="业务类型">
                <template slot-scope="scope">
                  <div>{{scope.row.businessType | payBusinessTypeFilter}}</div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="单据类型" prop="docTypeName"></el-table-column>
              <el-table-column align="center" label="单据号" prop="docCode"></el-table-column>
              <el-table-column align="center" label="付款金额" prop="ocAmt"></el-table-column>
              <el-table-column align="center" label="币种" prop="currencyTypeName"></el-table-column>
              <el-table-column align="center" label="收支项目" prop="ipItemName"></el-table-column>
            </el-table>
            <div>总金额:{{detailMoneyCount}}</div>
          </div>
        </el-card>

        <el-dialog title="关联应付单" :visible.sync="dialogFormVisible" width="65%" @close="closeDialogForm">
          <el-container style="width: 95%">
            <el-main>
              <el-table ref="shouldPaymentTable" :data="shouldPaymentList" height="350" v-loading="listLoading" element-loading-text="加载中" border fit highlight-current-row style="width: 100%;margin-top:5px">
                <el-table-column type="selection"></el-table-column>
                <el-table-column label="业务类型">
                  <template slot-scope="scope">
                    <div>{{scope.row.businessType | payBusinessTypeFilter}}</div>
                  </template>
                </el-table-column>
                <el-table-column label="单据类型" prop="docTypeName"></el-table-column>
                <el-table-column label="单据号" prop="docCode"></el-table-column>
                <el-table-column label="主体公司" prop="mainCompanyName"></el-table-column>
                <el-table-column label="到账日期" prop="termAccountDate"></el-table-column>
                <el-table-column label="立账日期" prop="buildAccountDate"></el-table-column>
                <el-table-column label="金额" prop="originalCurrencyBalance"></el-table-column>
                <el-table-column label="供应商" prop="partnerName"></el-table-column>
                <el-table-column label="单据状态">
                  <template slot-scope="scope">
                    <div>{{scope.row.status | shouldPaymentStatus}}</div>
                  </template>
                </el-table-column>
                <el-table-column label="来源单据" prop="sourceKey"></el-table-column>
                <el-table-column label="创建日期" prop="makeDate"></el-table-column>
                <el-table-column label="创建组织" prop="创建组织"></el-table-column>
              </el-table>
            </el-main>
          </el-container>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="addShouldPaymentClick">添加</el-button>
            <el-button type="primary" @click="closeDialogForm">取消</el-button>
          </div>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import {
  addPayment,
  updatePayment
} from '@/api/pay/payment'
import waves from '@/directive/waves' // 水波纹指令
import {
  getNcFileContrastPartnerList,
  getDepartmentList,
  getStaffList,
  getCompanyList,
  getBankInfoList,
  getFiscalPeriodList,
  getIncomePayItemList,
  getSettleTypeList,
  getCurrencyTypeList,
  getShouldPaymentList,
  getShouldPaymentTypeListByBusinessType,
  getBankAccountListByBankInfoId,
  getCashFlowLtemList,
  getShouldPaymentDetailByHeadId
} from '@/api/baseDataCommon'
export default {
  name: 'paymentForm',
  directives: {
    waves
  },
  data() {
    return {
      listLoading: false,
      dialogFormVisible: false,
      paymentForm: {
        paymentRowsDetailList: [],
        paymentDetailList: []
      },
      paymentFormRules: {
        settlCompanyId: [{ required: true, message: '结算公司不能为空' }],
        docType: [{ required: true, message: '单据类型不能为空' }],
        docDate: [{ required: true, message: '单据日期不能为空' }],
        useWay: [{ required: true, message: '付款用途不能为空' }],
        paymentDate: [{ required: true, message: '付款日期不能为空' }],
        partnerId: [{ required: true, message: '供应商不能为空' }],
        mainCompanyId: [{ required: true, message: '主体公司不能为空' }],
        agreementId: [{ required: true, message: '收付款协议不能为空' }],
        fiscalPeriod: [{ required: true, message: '会计期间不能为空' }],
        cashFlowLtem: [{ required: true, message: '现金流量不能为空' }]
      },
      shouldPaymentList: [],
      partnerList: [], // 供应商
      departmentList: [], // 部门
      staffList: [], // 业务员
      companyList: [], // 公司
      shouldPaymentTypeList: [], // 应付单类型
      bankInfoList: [],  //  银行
      fiscalPeriodList: [],  // 会计期间
      incomePayItemList: [], // 收支项目
      settleTypeList: [],  // 结算方式
      currencyTypeList: [],  // 币种
      bankAccountList: [], // 银行账号
      cashFlowLtemList: [], // 现金流量
      rowMoneyCount: 0, // 行总金额
      detailMoneyCount: 0 // 明细总金额
    }
  },
  created() {
    // 获取Nc供应商
    getNcFileContrastPartnerList().then(result => {
      this.$data.partnerList = result.data
    })
    // 获取部门
    getDepartmentList().then(result => {
      this.$data.departmentList = result.data
    })
    // 获取业务员
    getStaffList().then(result => {
      this.$data.staffList = result.data
    })
    // 获取公司
    getCompanyList().then(result => {
      this.$data.companyList = result.data
    })
    // 应付单类型
    // TODO 业务类型 70 80 90
    getShouldPaymentTypeListByBusinessType(['70', '80', '90']).then(result => {
      this.$data.shouldPaymentTypeList = result.data
    })
    // 获取银行
    getBankInfoList().then(result => {
      this.$data.bankInfoList = result.data
    })
    // 获取会计期间
    getFiscalPeriodList().then(result => {
      this.$data.fiscalPeriodList = result.data
    })
    // 获取收支项目
    getIncomePayItemList().then(result => {
      this.$data.incomePayItemList = result.data
    })
    // 获取结算方式
    getSettleTypeList().then(result => {
      this.$data.settleTypeList = result.data
    })
    // 币种
    getCurrencyTypeList().then(result => {
      this.$data.currencyTypeList = result.data
    })
    // 现金流量
    getCashFlowLtemList().then(result => {
      this.$data.cashFlowLtemList = result.data
    })
    // 更新赋值新数据
    if (this.$route.params.data) {
      this.$data.paymentForm = this.$route.params.data
    }
  },
  watch: {
    paymentForm: { // 金额监控
      handler(value, oldVaule) {
        this.$data.rowMoneyCount = 0
        this.$data.detailMoneyCount = 0
        // 行总额
        value.paymentRowsDetailList.forEach((v, i) => {
          this.$data.rowMoneyCount += v.ocAmt ? parseFloat(v.ocAmt) : 0
        })
        this.$data.rowMoneyCount = this.$data.rowMoneyCount.toFixed(2)
        // 明细总额
        value.paymentDetailList.forEach((v, i) => {
          this.$data.detailMoneyCount += v.ocAmt ? parseFloat(v.ocAmt) : 0
        })
        this.$data.detailMoneyCount = this.$data.detailMoneyCount.toFixed(2)
      },
      deep: true
    }
  },
  methods: {
    addPaymentClick() {
      // 新增提交付款单
      this.$refs['paymentForm'].validate(valid => {
        if (valid) {
          // // 付款明细
          // if (this.$data.paymentForm.paymentDetailList && this.$data.paymentForm.paymentDetailList.length > 0) {
          //   // 明细总额
          //   var paymentDetailOcAmt = 0
          //   // 付款行总额
          //   var paymentRowOcAmt = 0
          //   for (const index in this.$data.paymentForm.paymentDetailList) {
          //     paymentDetailOcAmt += parseFloat(this.$data.paymentForm.paymentDetailList[index].ocAmt)
          //   }

          //   for (const index in this.$data.paymentForm.paymentRowsDetailList) {
          //     paymentRowOcAmt += parseFloat(this.$data.paymentForm.paymentRowsDetailList[index].ocAmt)
          //   }
          //   if (paymentDetailOcAmt !== paymentRowOcAmt) {
          //     this.$notify({
          //       title: '信息提示',
          //       message: '付款金额必须和付款总额相等',
          //       type: 'error',
          //       duration: 2000
          //     })
          //     return
          //   }
          // }
          addPayment(this.$data.paymentForm).then(result => {
            // 清空
            this.$data.paymentForm = {}
            this.$data.paymentForm.paymentRowsDetailList = []
            this.$data.paymentForm.paymentDetailList = []
            if (result.code === 0) {
              this.$notify({
                title: '信息提示',
                message: '新增付款单成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '信息提示',
                message: result.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    updatePaymentClick() {
      // 更新付款单 submit
      this.$refs['paymentForm'].validate(valid => {
        if (valid) {
          updatePayment(this.$data.paymentForm).then(result => {
            if (result.code === 0) {
              this.$notify({
                title: '信息提示',
                message: '更新付款单成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '信息提示',
                message: result.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    relevanceShouldPaymentClick() { // 关联应付单
      if (!this.$data.paymentForm.settlCompanyId) {
        this.$refs['paymentForm'].validateField('settlCompanyId')
        this.$notify({
          title: '信息提示',
          message: '请选择结算公司',
          type: 'error',
          duration: 2000
        })
        return
      }

      if (!this.$data.paymentForm.partnerId) {
        this.$refs['paymentForm'].validateField('partnerId')
        this.$notify({
          title: '信息提示',
          message: '请选择供应商',
          type: 'error',
          duration: 2000
        })
        return
      }
      // 获取nc Code
      var ncCode = ''
      this.$data.partnerList.forEach((v) => {
        if (this.$data.paymentForm.partnerId === v.id) {
          ncCode = v.ncCode
        }
      })

      // 获取应付单
      getShouldPaymentList({
        // partnerId: this.$data.paymentForm.partnerId,
        ncCode: ncCode,
        settlCompanyId: this.$data.paymentForm.settlCompanyId
      }).then(result => {
        if (result.code === 0) {
          this.$data.shouldPaymentList = result.data
          this.$data.dialogFormVisible = true
        } else {
          this.$notify({
            title: '信息提示',
            message: result.message,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    closeDialogForm() {
      this.$data.dialogFormVisible = false
    },
    addPaymentFormRowClick() { // 添加付款单行
      this.paymentForm.paymentRowsDetailList.push({ payAccountCode: undefined })
    },
    deletePaymentFormRowClick() { // 删除付款单行
      if (this.$refs.paymentFormRowTable.selection.length > 0) {
        this.$refs.paymentFormRowTable.selection.forEach(element => {
          for (const index in this.$data.paymentForm.paymentRowsDetailList) {
            if (this.$data.paymentForm.paymentRowsDetailList[index].__ob__.dep.id === element.__ob__.dep.id) {
              this.$data.paymentForm.paymentRowsDetailList.splice(index, 1)
              break
            }
          }
        })
      }
    },
    addShouldPaymentClick() { // 添加选择应付单
      if (this.$refs.shouldPaymentTable.selection.length === 0) {
        this.$notify({
          title: '信息提示',
          message: '请选择应付单',
          type: 'error',
          duration: 2000
        })
        return
      }
      this.$data.paymentForm.paymentDetailList = [] // 清空
      for (const index in this.$refs.shouldPaymentTable.selection) {
        // 获取应付单详情
        getShouldPaymentDetailByHeadId(this.$refs.shouldPaymentTable.selection[index].id).then(result => {
          this.$data.paymentForm.paymentDetailList.push({
            businessType: this.$refs.shouldPaymentTable.selection[index].businessType, // 业务类型
            docType: this.$refs.shouldPaymentTable.selection[index].docType,  // 单据类型
            docTypeName: this.$refs.shouldPaymentTable.selection[index].docTypeName,  // 单据类型
            docCode: this.$refs.shouldPaymentTable.selection[index].docCode,  // 单据号
            ocAmt: this.$refs.shouldPaymentTable.selection[index].originalCurrencyBalance, // 付款金额（原币）
            currencyTypeId: result.data[0] ? result.data[0].currencyTypeId : undefined, // 币种
            currencyTypeName: result.data[0] ? result.data[0].currencyTypeName : undefined,  // 币种名称
            ipItemId: result.data[0] ? result.data[0].ipItemId : undefined, // 收支项目
            ipItemName: result.data[0] ? result.data[0].ipItemName : undefined // 收支名称
          })
        })
      }
      this.closeDialogForm()
    },
    selectBankInfoChange(scope, v) {  // 银行信息改变
      this.$data.paymentForm.paymentRowsDetailList[scope.$index].payAccountCode = undefined //  清空银行账号选择
      this.$data.bankAccountList[scope.$index] = [] // 清空 银行账号
      getBankAccountListByBankInfoId(scope.row.payBankId).then(result => {
        this.$set(this.$data.bankAccountList, scope.$index, result.data)
      })
    },
    cleanClick() {
      this.paymentForm = {
        paymentRowsDetailList: [],
        paymentDetailList: []
      }
    }
  }
}
</script>
<style scoped>

</style>
